#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import sys
import time

from flask import Response
import json
import gzip
from flask_restful import reqparse, Resource
from src.formats.insensitive_argument import CaseInsensitiveArgument
from src.formats import MapServiceManager
from src.routers.GetDataFromManager import GetSlpk_path, GetSlpkJson, GetSlpkRootJson, GetSlpkNodeJson, \
    GetSlpkNodepages, \
    GetSlpkGeometries, GetSlpkTextures, GetSlpkNodeSharedJson, GetSlpkSublayersJson, GetSlpkFile, GetZipFile

sys.path.append("../..")

# 全局变量
mapServiceManager = MapServiceManager.mapServiceManager


class ESRISlpkJson(Resource):
    def __init__(self):
        print('init ESRISlpkTileServer')
        self.parser = reqparse.RequestParser(
            argument_class=CaseInsensitiveArgument)
        self.parser.argument_class.case_sensitive = False
        self.parser.add_argument('f', type=str, location='args')
        # 第一个参数：验证的参数的名称,(location)：传递验证数据的方式 (type）：验证数据的逻辑
        # http://127.0.0.1:5001/20201104_200m_nnu_B1_ACA_Rec1_slpk/SceneServer?f=json

    def get(self, servicename):
        # data 是一个字典
        data = self.parser.parse_args()
        # 获取验证后的数据
        f = data.get('f')

        resp = ''
        if f == 'json':
            resp = Response(GetSlpkJson(servicename), status=200, mimetype='application/json')
            resp.headers['Content-Encoding'] = 'gzip'
            resp.headers['Access-Control-Allow-Origin'] = '*'
            resp.headers['Access-Control-Allow-Headers'] = 'Content-Type'
            resp.headers['Access-Control-Allow-Credentials'] = 'GET,POST,OPTIONS'
        else:
            resp = Response('Not Found',
                            status=404,
                            mimetype='text/javascript')
        return resp

class ESRISlpkRootJson(Resource):
    def __init__(self):
        print('init ESRISlpkRootJson')
        self.parser = reqparse.RequestParser(
            argument_class=CaseInsensitiveArgument)
        self.parser.argument_class.case_sensitive = False
        self.parser.add_argument('f', type=str, location='args')

    def get(self, servicename):
        data = self.parser.parse_args()
        f = data.get('f')

        resp = ''
        if f == 'json':
            # resp = 'json(' + json.dumps(GetSlpkRootJson(servicename)) + ')'
            resp = Response(GetSlpkRootJson(servicename), status=200, mimetype='application/json')
            resp.headers['Content-Encoding'] = 'gzip'
            resp.headers['Access-Control-Allow-Origin'] = '*'
            resp.headers['Access-Control-Allow-Headers'] = 'Content-Type'
            resp.headers['Access-Control-Allow-Credentials'] = 'GET,POST,OPTIONS'
        else:
            resp = Response(GetSlpkRootJson(servicename), status=200, mimetype='application/json')
            resp.headers['Content-Encoding'] = 'gzip'
            resp.headers['Access-Control-Allow-Origin'] = '*'
            resp.headers['Access-Control-Allow-Headers'] = 'Content-Type'
            resp.headers['Access-Control-Allow-Credentials'] = 'GET,POST,OPTIONS'
            # resp = Response('Not Found',
            #                 status=404,
            #                 mimetype='text/javascript')
        return resp


class ESRISlpkNodeJSON(Resource):
    def __init__(self):
        print('init ESRISlpkRootJson')
        self.parser = reqparse.RequestParser(
            argument_class=CaseInsensitiveArgument)
        self.parser.argument_class.case_sensitive = False
        self.parser.add_argument('f', type=str, location='args')
        # http://127.0.0.1:5001/Production_1_200M_100_SP_new/SceneServer/nodes/2247

    def get(self, servicename, tilenum):
        data = self.parser.parse_args()
        f = data.get('f')

        resp = ''
        if f == 'json':
            # resp = 'json(' + json.dumps(GetSlpkRootJson(servicename)) + ')'
            resp = Response(GetSlpkNodeJson(servicename, tilenum), status=200, mimetype='application/json')
            resp.headers['Content-Encoding'] = 'gzip'
            resp.headers['Access-Control-Allow-Origin'] = '*'
            resp.headers['Access-Control-Allow-Headers'] = 'Content-Type'
            resp.headers['Access-Control-Allow-Credentials'] = 'GET,POST,OPTIONS'
        else:
            resp = Response(GetSlpkNodeJson(servicename, tilenum), status=200, mimetype='application/json')
            resp.headers['Content-Encoding'] = 'gzip'
            resp.headers['Access-Control-Allow-Origin'] = '*'
            resp.headers['Access-Control-Allow-Headers'] = 'Content-Type'
            resp.headers['Access-Control-Allow-Credentials'] = 'GET,POST,OPTIONS'
            # resp = Response('Not Found',
            #                 status=404,
            #                 mimetype='text/javascript')
        return resp


class ESRISlpkSublayersJSON(Resource):
    def __init__(self):
        print('init ESRISlpkSublayersJSON')
        self.parser = reqparse.RequestParser(
            argument_class=CaseInsensitiveArgument)
        self.parser.argument_class.case_sensitive = False
        self.parser.add_argument('f', type=str, location='args')
        # http://127.0.0.1:5001/20211116slpk_AS3/SceneServer/sublayers/8

    def get(self, servicename, tilenum):
        data = self.parser.parse_args()
        f = data.get('f')

        resp = ''
        if f == 'json':
            # resp = 'json(' + json.dumps(GetSlpkRootJson(servicename)) + ')'
            resp = Response(GetSlpkSublayersJson(servicename, tilenum), status=200, mimetype='application/json')
            resp.headers['Content-Encoding'] = 'gzip'
            resp.headers['Access-Control-Allow-Origin'] = '*'
            resp.headers['Access-Control-Allow-Headers'] = 'Content-Type'
            resp.headers['Access-Control-Allow-Credentials'] = 'GET,POST,OPTIONS'
        else:
            resp = Response(GetSlpkSublayersJson(servicename, tilenum), status=200, mimetype='application/json')
            resp.headers['Content-Encoding'] = 'gzip'
            resp.headers['Access-Control-Allow-Origin'] = '*'
            resp.headers['Access-Control-Allow-Headers'] = 'Content-Type'
            resp.headers['Access-Control-Allow-Credentials'] = 'GET,POST,OPTIONS'
            # resp = Response('Not Found',
            #                 status=404,
            #                 mimetype='text/javascript')
        return resp


class ESRISlpkNodeSharedJSON(Resource):
    def __init__(self):
        print('init ESRISlpkNodeSharedJSON')
        self.parser = reqparse.RequestParser(
            argument_class=CaseInsensitiveArgument)
        self.parser.argument_class.case_sensitive = False
        self.parser.add_argument('f', type=str, location='args')

    def get(self, servicename, tilenum):
        data = self.parser.parse_args()
        f = data.get('f')

        result = GetSlpkNodeSharedJson(servicename, tilenum)
        # print(gzip.decompress(result).decode())
        resp = Response(result, status=200, mimetype='application/json')
        resp.headers['Content-Encoding'] = 'gzip'
        resp.headers['Access-Control-Allow-Origin'] = '*'
        resp.headers['Access-Control-Allow-Headers'] = 'Content-Type'
        resp.headers['Access-Control-Allow-Credentials'] = 'GET,POST,OPTIONS'
        return resp


class ESRISlpkNodepages(Resource):
    def __init__(self):
        print('init ESRISlpkTileServer')

    def get(self, servicename, filename):
        try:
            resp = Response(GetSlpkNodepages(servicename, filename), status=200, mimetype='application/json')
            resp.headers['Content-Encoding'] = 'gzip'
        except Exception as e:
            print(e)
            resp = Response(servicename + ' file ' + filename + ' Not Found',
                            status=404,
                            mimetype='text/javascript')

        resp.headers['Access-Control-Allow-Origin'] = '*'
        resp.headers['Access-Control-Allow-Headers'] = 'Content-Type'
        resp.headers['Access-Control-Allow-Credentials'] = 'GET,POST,OPTIONS'

        return resp


class ESRISlpkGeometries(Resource):
    def __init__(self):
        print('init ESRISlpkTileServer')

    def get(self, servicename, tilenum, filename):
        try:
            resp = Response(GetSlpkGeometries(servicename, tilenum, filename), status=200, mimetype='text/html')
            resp.headers['Content-Encoding'] = 'gzip'
        except Exception as e:
            print(e)
            resp = Response(servicename + ' file ' + filename + ' Not Found',
                            status=404,
                            mimetype='text/javascript')

        resp.headers['Access-Control-Allow-Origin'] = '*'
        resp.headers['Access-Control-Allow-Headers'] = 'Content-Type'
        resp.headers['Access-Control-Allow-Credentials'] = 'GET,POST,OPTIONS'

        return resp


class ESRISlpkTextures(Resource):
    def __init__(self):
        print('init ESRISlpkTileServer')

    def get(self, servicename, tilenum, filename):
        try:
            resp = Response(GetSlpkTextures(servicename, tilenum, filename), status=200, mimetype='text/html')
            resp.headers['Content-Encoding'] = 'gzip'
        except Exception as e:
            print(e)
            resp = Response(servicename + ' file ' + filename + ' Not Found',
                            status=404,
                            mimetype='text/javascript')

        resp.headers['Access-Control-Allow-Origin'] = '*'
        resp.headers['Access-Control-Allow-Headers'] = 'Content-Type'
        resp.headers['Access-Control-Allow-Credentials'] = 'GET,POST,OPTIONS'

        return resp


class ESRISlpk_path(Resource):
    def __init__(self):
        print('init ESRISlpkServer')

    def get(self, servicename, full_path):
        try:
            resp = Response(GetSlpk_path(servicename, full_path), status=200, mimetype='text/html')
            resp.headers['Content-Encoding'] = 'gzip'
        except Exception as e:
            # print(e)
            resp = Response(servicename + ' file ' + full_path + ' Not Found',
                            status=404,
                            mimetype='text/javascript')

        resp.headers['Access-Control-Allow-Origin'] = '*'
        resp.headers['Access-Control-Allow-Headers'] = 'Content-Type'
        resp.headers['Access-Control-Allow-Credentials'] = 'GET,POST,OPTIONS'

        return resp


# 路由处理
# 拿到包内文件/文件夹路径，并调用函数获取其数据
class ESRISlpk(Resource):
    def __init__(self):
        print('init ESRISlpkServer')

    def get(self, servicename, full_path):
        fileName = mapServiceManager.serviceList[servicename]['config']['file']
        file_ext = mapServiceManager.serviceList[servicename]['config']['fileExt']
        try:

            file, ziptype, mimetype = GetSlpkFile(servicename, full_path, fileName, file_ext)

            resp = Response(file, status=200, mimetype=mimetype)
            if ziptype == 'gzip':
                resp.headers['Content-Encoding'] = 'gzip'
        except Exception as e:
            print(e)
            resp = Response(servicename + ' file ' + full_path + ' Not Found',
                            status=404,
                            mimetype='text/javascript')

        resp.headers['Access-Control-Allow-Origin'] = '*'
        resp.headers['Access-Control-Allow-Headers'] = 'Content-Type'
        resp.headers['Access-Control-Allow-Credentials'] = 'GET,POST,OPTIONS'

        return resp

class Zip(Resource):
    def __init__(self):
        print('init Zip')

    def get(self, servicename, full_path):
        fileName = mapServiceManager.serviceList[servicename]['config']['file']
        file_ext = mapServiceManager.serviceList[servicename]['config']['fileExt']
        try:
            file, ziptype, mimetype = GetZipFile(servicename, full_path, fileName, file_ext)
            resp = Response(file, status=200, mimetype=mimetype)
            if ziptype == 'gzip':
                resp.headers['Content-Encoding'] = 'gzip'
        except Exception as e:
            print(e)
            resp = Response(servicename + ' file ' + full_path + ' Not Found',
                            status=404,
                            mimetype='text/javascript')

        resp.headers['Access-Control-Allow-Origin'] = '*'
        resp.headers['Access-Control-Allow-Headers'] = 'Content-Type'
        resp.headers['Access-Control-Allow-Credentials'] = 'GET,POST,OPTIONS'
        return resp
